//
//  SubTableView.m
//  
//
//  Created by xu on 15/11/8.
//
//

#import "LatterTableView.h"
#import "BaseViewController.h"
#import "LatterInfoViewController.h"
#import "MemberLetterDto.h"
#import "LatterCell.h"
#import "Util.h"

@implementation LatterTableView
{
    AFHTTPRequestOperationManager *_manager;
}


//  父类中已经添加了tableview的代理
-(void)initData{
    _nilArray = [[NSMutableArray alloc] init];
    _manager = [AFHTTPRequestOperationManager manager];
    NSString *url=[NSString stringWithFormat:@"%@Letter/GetMemberLettersByPage",BaseURL];

    NSDictionary *parameters = @{@"memberid": Getmemberid,@"Lastletterid":@"0",@"pageSize":@"20",@"signature":[Util getSignature:[NSString stringWithFormat:@"%@020",Getmemberid]]};
    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        NSArray *result = [dic valueForKey:@"Datas"];
        //NSLog(@"%@",dic);
        if (error==nil&&![result isEqual:[NSNull null]]&&result!=nil&&result.count!=0) {
            for (int i = 0; i<[result count]; i++) {
                NSDictionary *data= result[i];
                MemberLetterDto *m = [[MemberLetterDto alloc]init];
                [m setLetterId:[data valueForKey:@"LetterId"]];
                [m setLetterTitle:[data valueForKey:@"LetterTitle"]];
                [m setSendTime:[Util getDateTime:[data valueForKey:@"SendTime"] ]];
                [m setLetterContent:[data valueForKey:@"LetterContent"]];
                [m setLetterType:[[data valueForKey:@"LetterType"] intValue]];
                [m setStatus:[[data valueForKey:@"Status"] intValue]];
                [m setMemberLetterId:[data valueForKey:@"MemberLetterId"]];
                
                
                [_nilArray addObject:m];
            }
        }
        [self reloadData];
        [self doneLoadingTableViewData];
        if ([_nilArray count]<20) {
            [self setIsLastPage:YES];
        }else{
            [self setIsLastPage:NO];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        [self doneLoadingTableViewData];
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
}

-(void)initLastData{
    if (_nilArray!=nil&&_nilArray.count>0) {
        
    
    MemberLetterDto *m =[_nilArray objectAtIndex:[_nilArray count]-1];
    _manager = [AFHTTPRequestOperationManager manager];
    NSString *url=[NSString stringWithFormat:@"%@Letter/GetMemberLettersByPage",BaseURL];
    _Lastletterid =m.LetterId;
    NSDictionary *parameters = @{@"memberid":Getmemberid,@"Lastletterid":_Lastletterid,@"pageSize":@"20",@"signature":[Util getSignature:[NSString stringWithFormat:@"%@%@20",Getmemberid,_Lastletterid]]};
    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        NSArray *result = [dic valueForKey:@"Datas"];
        //NSLog(@"%@",dic);
        if (error==nil&&![result isEqual:[NSNull null]]&&result!=nil&&result.count!=0) {
            for (int i = 0; i<[result count]; i++) {
                NSDictionary *data= result[i];
                MemberLetterDto *m = [[MemberLetterDto alloc]init];
                [m setLetterId:[data valueForKey:@"LetterId"]];
                [m setLetterTitle:[data valueForKey:@"LetterTitle"]];
                [m setSendTime:[Util getDateTime:[data valueForKey:@"SendTime"] ]];
                [m setLetterContent:[data valueForKey:@"LetterContent"]];
                [m setLetterType:[[data valueForKey:@"LetterType"] intValue]];
                [m setStatus:[[data valueForKey:@"Status"] intValue]];
                [m setMemberLetterId:[NSNumber numberWithInt:[[data valueForKey:@"MemberLetterId"] floatValue]]];
                
                
                [_nilArray addObject:m];
                 NSMutableArray *indexPathArray = [NSMutableArray array];
                NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                [indexPathArray addObject:tempIndexPath];
                 [self insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
                
            }
            [self setIsLastPage:NO];
        }else{
            [self setIsLastPage:YES];
        }
        [self reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
    }
}
//实现TABLE方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _nilArray.count;
}


//每个cell调用的方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LatterCell *cell = [LatterCell createWithTableView:tableView];
    if (_nilArray!=nil&&_nilArray.count>0) {
        MemberLetterDto *ml = [_nilArray objectAtIndex:indexPath.row];
        cell.title.text = ml.LetterTitle;
        cell.content.text = ml.LetterContent;
        cell.time.text = ml.SendTime;
        cell.tintColor = RedColor;
        if (ml.Status!=1) {
            cell.state.hidden =YES;
        }else{
            
        }
        
        if (ml.LetterType==1) {
            cell.image.image = [UIImage imageNamed:@"xiaoxijiekuanbohui"];
        }else if(ml.LetterType==2){
            cell.image.image = [UIImage imageNamed:@"xiaoxitouzi"];
        }else{
            cell.image.image = [UIImage imageNamed:@"xiaoxitouzihuikuan"];
        }
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
     if (self.editing) { 
       //  [_idsDic setObject:indexPath forKey:[_nilArray objectAtIndex:indexPath.row]];
         [_idsArray addObject:[_nilArray objectAtIndex:indexPath.row]];
         //NSLog(@"%@",_idsArray);

         if (_idsArray.count == 0) {
             self.viewController.navigationItem.leftBarButtonItem.enabled = NO;
             self.viewController.navigationItem.leftBarButtonItem.tintColor = LightGray;
         }else{
             self.viewController.navigationItem.leftBarButtonItem.enabled = YES;
             self.viewController.navigationItem.leftBarButtonItem.tintColor = WhiteColor;
         }
     }else{
         LatterInfoViewController *l = [[LatterInfoViewController alloc] init];
         MemberLetterDto *ml = [_nilArray objectAtIndex:indexPath.row]; 
         [self.viewController.navigationController pushViewController:l animated:YES];
         [l setMlid:[[[NSNumberFormatter alloc] init] stringFromNumber:ml.MemberLetterId]];
         [l setLid: [[[NSNumberFormatter alloc] init] stringFromNumber:ml.LetterId]];
         [tableView deselectRowAtIndexPath:indexPath animated:NO];
     }

    
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
  //  [_idsDic removeObjectForKey:[_nilArray objectAtIndex:indexPath.row]];
    //NSLog(@"%@",_idsArray);
    [_idsArray removeObject:[_nilArray objectAtIndex:indexPath.row]];
    //NSLog(@"%@",_idsArray);

    if (_idsArray.count == 0) {
        self.viewController.navigationItem.leftBarButtonItem.enabled = NO;
        self.viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithWhite:1 alpha:1];
    }else{
        self.viewController.navigationItem.leftBarButtonItem.enabled = YES;
//        self.viewController.navigationItem.leftBarButtonItem.tintColor = WhiteColor;
    }
    
    
}
@end
